package com.cqc.jdk8.Jutil.stream;

import com.cqc.eb.UserEB;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author cui
 * @date 2024/6/30 12:58
 * @description
 **/
public class PeekTest {

    List<UserEB> userEBList1 = null;

    @Before
    public void before() {
        //串行 并行
        userEBList1 = getUserList1();
    }


    @Test
    public void peek() {
        UserEB w = new UserEB("w", 10);
        UserEB x = new UserEB("x", 11);
        UserEB y = new UserEB("y", 12);

        Stream.of(w, x, y)
                .peek(e -> {
                    e.setName(e.getAge() + e.getName());
                }) //重新设置名字 变成 年龄+名字
                .forEach(e -> System.out.println(e.toString()));
    }

    /**
     * peek 不建议使用,会改变原有的数据。consumer
     */
    @Test
    public void peek2() {
        //peek()  foreach() 都会改变原有的集合
        List<UserEB> collect = userEBList1.stream()
                .peek(user -> user.setAge(user.getAge() + 10))
                .collect(Collectors.toList());
        System.out.println(collect.get(0).getAge());
        userEBList1
                .forEach(user -> user.setAge(user.getAge() + 10));
        System.out.println(userEBList1.get(0).getAge());
    }

    private static List<UserEB> getUserList1() {
        List<UserEB> list = new ArrayList<>();
        UserEB w = new UserEB("w", 10);
        UserEB x = new UserEB("x", 11);
        UserEB y = new UserEB("y", 12);
        list.add(w);
        list.add(x);
        list.add(y);
        return list;
    }

}
